var express = require('express');
var router = express.Router();

var crypto = require('crypto');

var user = require('../models/user');
var goods = require('../models/goods');
var collect = require('../models/collect');
var upload = require('../models/picture');
var cart = require('../models/cart');
var chat = require('../models/chat');

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 用户登录接口
router.post('/login', function (req, res, next) {
  if (!req.body.username) {
    res.json({ status: 1, message: "用户名为空" });
  }
  if (!req.body.password) {
    res.json({ status: 1, message: "密码为空" });
  }
  user.findUserLogin(req.body.username, req.body.password, function (err, userSave) {
    if (userSave) {
      if (userSave.userStop == true) {
        res.json({ status: 1, message: "账号已被停用" });
      } else {
        var after_token = getMD5Password(userSave._id);
        res.json({ status: 0, message: "用户登录成功", data: { token: after_token, user: userSave } })
      }
    } else {
      res.json({ status: 1, message: "用户名或者密码错误" })
    }
  })
});

// 用户注册接口
router.post('/register', function (req, res, next) {
  if (!req.body.username) {
    res.json({ status: 1, message: "用户名为空" });
  }
  if (!req.body.password) {
    res.json({ status: 1, message: "密码为空" });
  }
  if (!req.body.userMail) {
    res.json({ status: 1, message: "用户邮箱为空" });
  }
  if (!req.body.userPhone) {
    res.json({ status: 1, message: "用户手机为空" });
  }
  user.findByUsername(req.body.username, function (err, userSave) {
    if (userSave) {
      // 用户已注册
      res.json({ status: 1, message: "用户已注册" });
    } else {
      const registerUser = new user({
        username: req.body.username,
        password: req.body.password,
        userMail: req.body.userMail,
        userPhone: req.body.userPhone,
        userImg: 'http://localhost:3000/uploadcache/upload_a6ebb92781e98e4239ad04b4e255535c.jpg',
        userAdmin: 0,
        userStop: 0,
        userSex: '', // 性别
        userAddress: [], // 收货地址
        userSchool: '' // 学校
      });
      registerUser.save(function () {
        res.json({ status: 0, message: "注册成功" })
      })
    }
  });
});

// 更改用户信息
router.post('/update', function (req, res, next) {
  let obj = {
    userMail: req.body.userMail,
    userPhone: req.body.userPhone,
    userImg: req.body.userImg,
    userSex: req.body.userSex, // 性别
    userAddress: req.body.userAddress, // 收货地址
    userSchool: req.body.userSchool // 学校
  }
  user.update({ _id: req.body._id, }, obj, function (err, data) {
    if (err) {
      res.json({ status: 1, message: "修改失败", data: err });
    } else {
      res.json({ status: 0, message: "修改成功", data: data });
    }
  })
})

// 用户收藏接口
router.post('/collect', function (req, res, next) {
  collect.findById(req.body.username, req.body._id, function (err, userCollect) {
    if (userCollect) {
      res.json({ status: 1, message: "该商品已收藏" });
    } else {
      if (req.body.time) {
        const collectUser = new collect({
          collectUser: req.body.username, // 收藏用户
          collectTime: req.body.time, // 收藏时间
          collectGoods: req.body._id, // 收藏商品
        });
        // 收藏成功后将收藏数量加1
        goods.findById(req.body._id, function (err, getGoods) {
          goods.update({ _id: req.body._id }, { goodsCollect: getGoods.goodsCollect + 1 }, function (err, data) {
            res.json({ status: 0, message: "更新成功", data: err });
          })
        })
        collectUser.save(function () {
          // res.json({ status: 0, message: "收藏成功" });
        });
      }
    }
  });
});

// 用户取消收藏
router.post('/uncollect', function (req, res, next) {
  collect.remove({ _id: req.body._id }, function (err, delCollect) {
    res.json({ status: 0, message: "删除成功", data: delCollect });
    goods.findById(req.body.id, function (err, getGoods) {
      goods.update({ _id: req.body.id }, { goodsCollect: getGoods.goodsCollect - 1 }, function () { })
    })
  })
})

// 用户添加商品
router.post('/addGoods', function (req, res, next) {
  if (!req.body.goodsName) {
    res.json({ status: 1, message: "商品信息为空" });
  }
  if (!req.body.goodsInfo) {
    res.json({ status: 1, message: "使用情况为空" });
  }
  if (!req.body.goodsLocation) {
    res.json({ status: 1, message: "所在学校为空" });
  }
  if (!req.body.goodsPrice) {
    res.json({ status: 1, message: "交易价格为空" });
  }
  if (!req.body.goodsOrigin) {
    res.json({ status: 1, message: "原始价格为空" });
  }
  if (!req.body.goodsImages) {
    res.json({ status: 1, message: "商品图片为空" });
  }
  if (!req.body.goodsClassify) {
    res.json({ status: 1, message: "商品分类为空" });
  }
  if (!req.body.goodsTime) {
    res.json({ status: 1, message: "商品购买时间为空" });
  }
  if (!req.body.goodsAmount) {
    res.json({ status: 1, message: "商品剩余数量为空" });
  }
  if (!req.body.goodsReturn) {
    res.json({ status: 1, message: "商品剩余数量为空" });
  }
  const goodsUser = new goods({
    goodsName: req.body.goodsName, // 商品信息
    goodsInfo: req.body.goodsInfo,  // 使用情况
    goodsLocation: req.body.goodsLocation, // 所在学校
    goodsPrice: req.body.goodsPrice, // 价格
    goodsOrigin: req.body.goodsOrigin, // 原始价格
    goodsImages: req.body.goodsImages, // 商品图片
    goodsUser: req.body.goodsUser, // 上传用户
    goodsClassify: req.body.goodsClassify, // 商品分类
    goodsTime: req.body.goodsTime, // 商品购买时间
    goodsAmount: req.body.goodsAmount, // 商品剩余数量
    goodsReturn: req.body.goodsReturn, // 是否支持退货
    goodsCollect: 0, // 商品收藏数量
  });
  goodsUser.save(function () {
    res.json({ status: 0, message: "添加成功" });
  })
});

// 用户编辑商品
router.post('/editGoods', function (req, res, next) {
  if (!req.body.goodsName) {
    res.json({ status: 1, message: "商品信息为空" });
  }
  if (!req.body.goodsInfo) {
    res.json({ status: 1, message: "使用情况为空" });
  }
  if (!req.body.goodsLocation) {
    res.json({ status: 1, message: "所在学校为空" });
  }
  if (!req.body.goodsPrice) {
    res.json({ status: 1, message: "交易价格为空" });
  }
  if (!req.body.goodsOrigin) {
    res.json({ status: 1, message: "原始价格为空" });
  }
  if (!req.body.goodsImages) {
    res.json({ status: 1, message: "商品图片为空" });
  }
  if (!req.body.goodsClassify) {
    res.json({ status: 1, message: "商品分类为空" });
  }
  if (!req.body.goodsTime) {
    res.json({ status: 1, message: "商品购买时间为空" });
  }
  if (!req.body.goodsAmount) {
    res.json({ status: 1, message: "商品剩余数量为空" });
  }
  if (!req.body.goodsReturn) {
    res.json({ status: 1, message: "商品剩余数量为空" });
  }
  let obj = {
    goodsName: req.body.goodsName, // 商品信息
    goodsInfo: req.body.goodsInfo,  // 使用情况
    goodsLocation: req.body.goodsLocation, // 所在学校
    goodsPrice: req.body.goodsPrice, // 价格
    goodsOrigin: req.body.goodsOrigin, // 原始价格
    goodsImages: req.body.goodsImages, // 商品图片
    goodsClassify: req.body.goodsClassify, // 商品分类
    goodsTime: req.body.goodsTime, // 商品购买时间
    goodsAmount: req.body.goodsAmount, // 商品剩余数量
    goodsReturn: req.body.goodsReturn, // 是否支持退货
  }
  goods.update({ _id: req.body.goodsId }, obj, function (err, data) {
    if (err) {
      res.json({ status: 1, message: "修改失败", data: err });
    } else {
      res.json({ status: 0, message: "修改成功", data: data });
    }
  })
})

// 用户删除商品
router.post('/delGoods', function (req, res, next) {
  if (!req.body.goodsId) {
    res.json({ status: 1, message: "商品id传递失败" });
  }
  goods.remove({ _id: req.body.goodsId }, function (err, delGoods) {
    res.json({ status: 0, message: "删除成功", data: delGoods });
  })
});

// 用户上传图片
router.post('/upload', function (req, res, next) {
  upload.upload(req, res);
});

// 创建房间信息
router.post('/chat', function (req, res, next) {
  const chatRoom = new chat({
    chatRoom: req.body.chatRoom, // 房间名称
    userOne: req.body.userOne, // 发件人
    userTwo: req.body.userTwo, // 收件人
    imgOne: req.body.imgOne, // 发件人头像
    imgTwo: req.body.imgTwo, // 收件人头像
    isRead: false, // 是否查看
    chatContent: [], // 聊天内容
    chatTime: req.body.chatTime, // 聊天时间
  });
  chatRoom.save(function () {
    res.json({ status: 0, message: '创建成功' });
  })
})

// 保存聊天记录
router.post('/upchat', function (req, res, next) {
  const obj = {
    chatTime: req.body.chatTime,
    chatContent: req.body.chatContent
  };
  chat.update({ chatRoom: req.body.chatRoom }, obj, function (err, data) {
    if (err) {
      res.json({ status: 1, message: "修改失败", data: err });
    } else {
      res.json({ status: 0, message: "修改成功", data: data });
    }
  });
});

// 用户添加购物车
router.post('/addCart', function (req, res, next) {
  cart.findByGoodsId(req.body.goodsId, function (err, data) {
    if (data) {
      cart.update({ goodsId: req.body.goodsId }, { goodsCount: data.goodsCount + 1 }, function (err, data) {
        if (err) {
          res.json({ status: 1, message: "修改失败", data: err });
        } else {
          res.json({ status: 0, message: "修改成功", data: data });
        }
      })
    } else {
      const goodsCart = new cart({
        username: req.body.username,
        goodsId: req.body.goodsId,
        goodsCount: 1
      })
      goodsCart.save(function () {
        res.json({ status: 0, message: '创建成功' })
      })
    }
  })
});

// 查找用户的购物车
router.post('/findCart', function (req, res, next) {
  cart.findByUsername(req.body.username, function (err, data) {
    if (err) {
      res.json({ status: 1, message: '查找失败' })
    } else {
      res.json({ status: 0, message: '查找成功', data: data })
    }
  })
})

// 修改用户购物车，修改数量
router.post('/editCart', function (req, res, next) {
  cart.update({ goodsId: req.body.goodsId }, { goodsCount: req.body.goodsCount }, function (err, data) {
    if (err) {
      res.json({ status: 1, message: '修改失败' })
    } else {
      res.json({ status: 0, message: '修改成功', data: data })
    }
  })
})

// 删除用户购物车商品
router.post('/delCart', function (req, res, next) {
  cart.remove({ goodsId: req.body.goodsId }, function (err, data) {
    if (err) {
      res.json({ status: 1, message: "删除失败", data: err });
    } else {
      res.json({ status: 0, message: "删除成功", data: data });
    }
  })
})

function getMD5Password (id) {
  var md5 = crypto.createHash('md5');
  return md5.update(id + '').digest('hex');
}

module.exports = router;
